local Players = game:GetService("Players")
local ConnectClass=_G.CommonOHOH.load.Connect();
local CommonOHOH = _G.CommonOHOH;
local M = CommonOHOH.class.new(script, CommonOHOH.files.Car());

local CarTool=_G.CommonOHOH.load.CarTool();
local CallBackManager = CommonOHOH.load.CallBackManager();

local InstanceManager = CommonOHOH.load.InstanceManager();
local runService =game:GetService("RunService")

local game_cfg= CommonOHOH.config.Game
local gWalkSpeed=game_cfg.WalkSpeed

local ColliderGroup = CommonOHOH.load.ColliderGroup();
local ColliderManager = CommonOHOH.load.ColliderManager();

-- 初始化一辆车
function M.new(...)
	return M(...);
end;

function M.ctor(self,player,bodyId,flagId,ringId,tailId,weaponId)--构造函数

    -- self.DataStore = player:GetComponent(_G.ServerOHOH.load.Server_PlayerDataComponent());
   
	M.super.ctor(self,player,bodyId,flagId,ringId,tailId,weaponId);

    self.playerList={} 
    self.player =player
    self.userId=self.player:GetUserId()
    self.LeaveCarEvent=ConnectClass.new() --离开车辆事件
    self.SitCarEvent=ConnectClass.new() --离开车辆事件
    -- CallBackManager:AddRbxConnect(self,game.Players.PlayerRemoving, function(obj,player) --车上的玩家退出游戏 处理
    --     self.playerList[player.UserId]=nil
    --     print("玩家离开",player.UserId)
        
	-- end);
    -- self:Start()
    self:Init()
end;

--初始化
function M.Init(self)
    ColliderManager:SetAllGroup(self:GetModel(), ColliderGroup.character);

    local proximityPrompt = Instance.new("ProximityPrompt")
    proximityPrompt.ActionText = "Drive"
    proximityPrompt.ObjectText = "我的车"
    proximityPrompt.KeyboardKeyCode = Enum.KeyCode.E
    proximityPrompt.RequiresLineOfSight = false
    proximityPrompt.Parent =  self:GetBody():GetInstance()
    --self.seat.PromptSitState.Value = true
    self.prompt = proximityPrompt

    local leavePrompt = Instance.new("ProximityPrompt")
    leavePrompt.ActionText = "离开"
    leavePrompt.ObjectText = "我的车"
    leavePrompt.KeyboardKeyCode = Enum.KeyCode.Space
    leavePrompt.RequiresLineOfSight = false
    
    leavePrompt.UIOffset = Vector2.new(0, 200)

    leavePrompt.Parent =  self:GetBody():GetInstance()
    --self.seat.PromptSitState.Value = true
    self.leavePrompt = leavePrompt

    self.prompt.Enabled =false
    self.leavePrompt.Enabled =false

    --坐下按钮
    proximityPrompt.Triggered:Connect(function(player)
        if player.UserId==self:GetUserId() then
            self:AddProcess(function()
                self.prompt.Enabled =false
                
                self.SitCarEvent:Action()
                task.wait(0.2)
                self.leavePrompt.Enabled =true
            end)
        else
           print("这不是你的车")
        end
    end)
    
--离开按钮
    leavePrompt.Triggered:Connect(function(player)
        if player.UserId==self:GetUserId() then
            self:AddProcess(function()
                self.leavePrompt.Enabled =false
                
                self.LeaveCarEvent:Action()

                task.wait(0.2)
                self.prompt.Enabled =true
                print("离开")
               
            end)
        end
    end)
end




function M.AddCharacter(self,main_inst)
    M.super.AddCharacter(self,main_inst);
   local character InstanceManager:FindObject(main_inst)
   if character and character.player then
        self.playerList[character.player:GetUserId()]=character.player
   end
end



function M.dtor(self)
    self:SetDriveConnectionOff()
   
	M.super.dtor(self);
end;

-- function M.Start(self)
--     self:AddProcess(function()
--         -- self:AddCharacter(self.player.character.main_inst) 
--         self:AddCharacterToDrive(self.player.character.main_inst) --将玩家放置到车上
--         -- self:Wait(1)
--         -- self:AnchoredSwitch(false) --取消锚固

--     end)
-- end

--
-- function M.Leave(self)
--     self:AddProcess(function()
--         self:AnchoredSwitch(false) --取消锚固
--         self:RemoveCharacterToDrive(self.player.character.main_inst) --将玩家放置到车上
--         if self.sitAnimationTrack then
--             self.sitAnimationTrack:Stop()
--         end
--         self:Wait(1)
--     end)
-- end


function M.CustomDrive(self)
    self.CarUsing = true
    --添加humanoid
    local CarModel =self:GetModel()
    local humanoid=self.player.character.main_inst.Humanoid

    self.CarHumanoid= Instance.new("Humanoid",CarModel)
    CarModel.HumanoidRootPart.Anchored=true
    CarModel.Humanoid.WalkSpeed=0
    CarModel.HumanoidRootPart.Anchored=false
    
    --让人物坐在椅子上
    local seatlist= self:GetBody():GetSeatList()
    for _,s in pairs(seatlist)  do
        if  not s:GetAttribute("isUsing") then
            -- self.player.character.main_inst.HumanoidRootPart:PivotTo( s:GetPivot())
            task.wait(0.2)
            s.Disabled = false
            s:SetAttribute("isUsing",true)
            print("sit",s,humanoid)
            s:Sit(humanoid)
            break

        end
    end
    --禁用人物humanoid
	humanoid.WalkSpeed=0
	humanoid.DisplayDistanceType=Enum.HumanoidDisplayDistanceType.None
    
    --替换人物humanoid
	local Character=self.player.character.main_inst
	self.sysCharacter=Character
	self.player.main_inst.Character=CarModel
	Character.Parent=CarModel
	
	task.wait(0.1)
    --设置车辆humanoid
	CarModel.Humanoid.WalkSpeed =gWalkSpeed*2
	CarModel.Humanoid.AutoJumpEnabled = false;
	CarModel.Humanoid.UseJumpPower = true;
	CarModel.Humanoid.JumpPower=0


    humanoid:ChangeState(Enum.HumanoidStateType.Seated) 
    
    --监听车辆humanoid属性来同步到 钻头和尾气特效
    if not  self.DriveConnection then
        self.DriveConnection =runService.Heartbeat:Connect(function(deltaTime)

            local humanVelocity = CarModel.HumanoidRootPart.AssemblyLinearVelocity.Magnitude
           
            -- print("humanVelocity",humanVelocity)
            if humanVelocity>0.5 then
                self:SetEmitterStatus(true)
                self:SetDrillingSpeed(humanVelocity)
            else
                --关闭旋转
                self:SetEmitterStatus(false)
                self:SetDrillingSpeed(0)
                --关闭特效
            end
        end)
    end
    -- return self.DriveConnection
    -- self:CustomSelfDrive()
end

function M.CustomLeaveCar(self)
    self.CarUsing = false
    if  self.DriveConnection then
        self.DriveConnection:Disconnect()
        self.DriveConnection =nil
    end
    local CarModel =self:GetModel()
    local humanoid= self.sysCharacter.Humanoid
  
	humanoid.WalkSpeed=0
	humanoid.DisplayDistanceType=Enum.HumanoidDisplayDistanceType.Viewer
    -- CarModel.HumanoidRootPart.Anchored=true

	self.CarHumanoid.WalkSpeed=0
    task.wait(0.1)
	
	local Character=self.sysCharacter 
	self.player.main_inst.Character=Character
    Character.Parent = workspace 
    task.wait(0.1)
	
	CarModel.Parent=workspace

    local seat= self:GetBody():GetSeatList()
    for _,s in pairs(seat)  do
        if  s:GetAttribute("isUsing") then
            s:SetAttribute("isUsing",false)
            s.Disabled = true
            
        end
    end
    self.CarHumanoid:Destroy()
    self.CarHumanoid = nil
	
	Character:WaitForChild("Humanoid"):ChangeState(Enum.HumanoidStateType.Jumping)
	Character:WaitForChild("Humanoid").WalkSpeed=gWalkSpeed
	task.wait(0.1)

	self.sysCharacter=nil
    
end;


-- 定义一个函数，让人物移动到当前点位
function M.moveToNextPoint(self)
    print("move to next___________________________________________________________")
    if self.battleEnd then
        print("battel nil__________________________________________________________")
        self.battleEnd = nil
        return
    end
    -- -- 获取当前点位
    local targetPosition = self.MovePoints[self.currentIndex]
    
    local  success = false
    while not success do
        if self.battleEnd  then
            print("battel nil__________________________________________________________")
            self.battleEnd = nil--or not self:GetModel():FindFirstChild("Humanoid")
            return
        end
        self:GetModel().Humanoid:MoveTo(targetPosition)
        local distance = (self:GetModel().HumanoidRootPart.Position - targetPosition).Magnitude
        if distance < 50 then
            success = true
        else
            task.wait(0.1)
        end
    end
    -- self:GetModel().Humanoid:MoveTo(targetPosition)
    -- self:GetModel().Humanoid.MoveToFinished:Wait()
    
    -- 更新下一个点位的索引（循环处理）
    self.currentIndex = self.currentIndex + 1
    if self.currentIndex > #self.MovePoints then
        -- self.currentIndex = 1 -- 回到第一个点
        print("终止移动__________________________________________________________")
        return --终止移动
    end
    
    -- 继续移动
    self:moveToNextPoint()
end

--自动化测试开车（按照点位MoveTo）（未使用）
function M.CustomAutoDrive(self,folder)
    local wayFolder = folder
    if not wayFolder then
        warn("Folder 'Way' not found in workspace!")
        return
    end
    
    local parts = {} -- 用来存储按编号排序的 Part
    
    -- 遍历文件夹中的所有子对象
    for _, child in pairs(wayFolder:GetChildren()) do
        if child:IsA("BasePart") and tonumber(child.Name) then
            table.insert(parts, child)
        end
    end
    
    -- 按名称（编号）排序
    table.sort(parts, function(a, b)
        return tonumber(a.Name) < tonumber(b.Name)
    end)
    
   
    -- local CarModel = self:GetModel()
    self.MovePoints = {}
    -- 遍历排序后的 Part，获取它们的位置
    for _, part in ipairs(parts) do
        -- print("Part Name:", part.Name, "Position:", part.Position)
        table.insert(self.MovePoints, part.Position)
    end
    print("Part List______________:",self.MovePoints)
    self.currentIndex = 1
    self:moveToNextPoint()
    -- local id = 1
    -- for _, part in ipairs(parts) do
    --     print("开始移动",id)
    --     id=id+1
    --     local  success = false
        
        
        -- while not success do
        --     print("true")
        --     CarModel.Humanoid:MoveTo(part.Position)
        --      local distance = (CarModel.HumanoidRootPart.Position - part.Position).Magnitude
        --     if distance < 30 then
        --         success = true
        --     else
        --         task.wait(0.1)
        --     end
           
        -- end
    -- end

end
------------------------------------------------------------------

--获取车辆使用者ID
function M.GetUserId(self)
    return self.userId
end

-- 获取车上的所有玩家
function M.GetAllPlayer(self)
    local list={}
    for userId,player in pairs(self.playerList) do
        table.insert(list,player)
    end
    return list
end

 --获取车辆使用者ID
function M.GetCarUsing(self)
    return self.CarUsing
end

-------------------------------------------------------------------
--设置提示是否启用 参数 true 启用| false 禁用
function M.SetPromptStatus(self,Enabled)
    if Enabled then
        self.prompt.Enabled =true
        self.leavePrompt.Enabled =false
    else
        self.prompt.Enabled =false
        self.leavePrompt.Enabled =false
    end
end
function M.SetCanCollide(self,canCollide)
    self:GetWeapon():GetTouchPart().CanCollide = canCollide
end
function M.SetSeatDisabled(self)
    local seatlist= self:GetBody():GetSeatList()
        for _,s in pairs(seatlist)  do
           s.Disabled = true
        end
end
function M.SetCanCollide(self,canCollide)
    self:GetWeapon():GetTouchPart().CanCollide = canCollide
end
---设置车辆速度
function M.SetCarHumanoidSpeed(self,speed)
    if speed and self.CarHumanoid then
        self.CarHumanoid.WalkSpeed =speed
    end
end

function M.SetDriveConnectionOff(self)
    if  self.DriveConnection then
        self.DriveConnection:Disconnect()
        self.DriveConnection =nil
    end
end

function M.KillCharacter(self)
    local Character = self.player.main_inst.Character
    if Character then
       
       if Character.Humanoid.Health then
        Character.Humanoid.Health = 0
        end
    end
end

return M